package com.zjp.blog.controller;

import com.zjp.blog.base.globalValName;
import com.zjp.blog.data.model.User;
import com.zjp.blog.service.UserService;
import com.zjp.blog.utils.MD5;
import com.zjp.blog.utils.Validation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;

/**
 * @author pj_zhong
 * @email pj_zhong@163.com / pj_zhong@gmail.com
 */
@Controller
public class LoginController extends BaseController {

    private static final Logger logger = LogManager.getLogger(LoginController.class);

    private static String page_login="/manage/admin/login";
    private static String to_login="/login";

    @Autowired
    UserService service;

    @RequestMapping(value = {"login","tologin"},method = RequestMethod.GET)
    public String toLogin()
    {
        return page_login;
    }

    @RequestMapping(value= "login",method = RequestMethod.POST)
    public String login(@RequestParam(value = "userEmail",defaultValue = "") String username,
                        @RequestParam(value = "password",defaultValue = "") String password,
                        ModelMap map) throws Exception {

        if(Validation.isEmpty(username)|| Validation.isEmpty(password)) {
            map.addAttribute("errorMsg","Account and Password Can't not be blank");
            return page_login;
        }

        User user = service.selectByEmail(username);
        if(user ==null || !MD5.md5(password).equals(user.getPassword())) {
            addError(map,"Account or Password error");
            return page_login;
        }

        getSession().setAttribute(globalValName.user.toString(),user);
        logger.info("Login:" + user + " " + new Date());
        return "redirect:" + "/manage";
    }

    @RequestMapping("logout")
    public String logout()
    {
        getSession().setAttribute(globalValName.user.toString(),null);
        getSession().invalidate();

        return  "redirect:/login";
    }
}
